using System;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using HengTong.Model;
using HengTong.Model._Admin;
using HengTong.Model.Db.Hr;
using WalkingTec.Mvvm.Core;
using UUIDNext;
using HengTong.Model.Db.Hr.Bill;
using HengTong.Model.Db.System;
using HengTong.ViewModel._Admin.SysUserJobPositionVms;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Wtm.Models;


namespace HengTong.ViewModel.Hr.SysHrJobAssignmentRequestBillEntryVms
{
    public partial class SysHrJobAssignmentRequestBillEntryVm : CrudVm<SysHrJobAssignmentRequestBillEntry>
    {
        public SysHrJobAssignmentRequestBillEntryVm()
        {
            SetInclude(x => x.Person);
            SetInclude(x => x.JobPosition);
            SetInclude(x => x.Group);
            SetInclude(x => x.Org);
            SetInclude(x => x.JobAssignment);
        }

        protected override void InitVM()
        {
        }

        public override async Task DoAddAsync()
        {
            // 1. 检查人员是否为试用期状态
            if (Entity.PersonId.HasValue)
            {
                var person = await DC.Set<SysPerson>()
                    .AsNoTracking()
                    .FirstOrDefaultAsync(p => p.ID == Entity.PersonId);

                if (person == null)
                {
                    MSD.AddModelError(" ", $"未找到工号为 {Entity.StaffNo} 的人员档案");
                    return;
                }

                if (person.State != PersonState.试用期)
                {
                    MSD.AddModelError(" ", $"人员 {person.Name}({person.StaffNo}) 不是试用期状态，当前状态为：{person.State}");
                    return;
                }

                // 2. 检查人员是否已经在其他流程中
                var existingEntry = await DC.Set<SysHrJobAssignmentRequestBillEntry>()
                    .Include(e => e.JobAssignment)
                    .AsNoTracking()
                    .FirstOrDefaultAsync(e => e.PersonId == Entity.PersonId &&
                                              e.JobAssignment.WorkflowStatus != WorkflowStatus.已完成 &&
                                              e.JobAssignment.WorkflowStatus != WorkflowStatus.已取消);

                if (existingEntry != null)
                {
                    MSD.AddModelError(" ", $"人员 {person.Name}({person.StaffNo}) 已经存在于另一个未完成的岗位分配流程中");
                    return;
                }
            }

            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }

            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            // 1. 检查人员是否为试用期状态
            var person = await DC.Set<SysPerson>()
                .AsNoTracking()
                .FirstOrDefaultAsync(p => p.ID == Entity.PersonId);

            if (person == null)
            {
                MSD.AddModelError(" ", $"未找到工号为 {Entity.StaffNo} 的人员档案");
                return;
            }

            if (person.State != PersonState.试用期)
            {
                MSD.AddModelError(" ", $"人员 {person.Name}({person.StaffNo}) 不是试用期状态，当前状态为：{person.State}");
                return;
            }

            // 2. 检查人员是否已经在其他流程中
            var existingEntry = await DC.Set<SysHrJobAssignmentRequestBillEntry>()
                .Include(e => e.JobAssignment)
                .AsNoTracking()
                .FirstOrDefaultAsync(e => e.PersonId == Entity.PersonId &&
                                          e.JobAssignment.WorkflowStatus != WorkflowStatus.已完成 &&
                                          e.JobAssignment.WorkflowStatus != WorkflowStatus.已取消 &&
                                          e.ID != Entity.ID);

            if (existingEntry != null)
            {
                MSD.AddModelError(" ", $"人员 {person.Name}({person.StaffNo}) 已经存在于另一个未完成的岗位分配流程中");
                return;
            }
            
            using var transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(5)
                },
                TransactionScopeAsyncFlowOption.Enabled);

            try
            {
                if (Entity is IBasePoco poco)
                {
                    poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                    poco.UpdateTime = DateTime.Now;
                }
                await base.DoEditAsync(updateAllFields);
                
                // 更新人员档案表的公司部门岗位
                var updatedRows = await DC.Set<SysPerson>()
                    .Where(p => p.ID == person.ID)
                    .ExecuteUpdateAsync(p => p
                        .SetProperty(x => x.OrgId, Entity.OrgId)
                        .SetProperty(x => x.GroupId, Entity.GroupId)
                        .SetProperty(x => x.JobPositionId, Entity.JobPositionId));
                if (updatedRows == 0)
                {
                    var error = $"未找到ID为 {person.ID} 的人员档案";
                    MSD.AddModelError(" ", error);
                    return;
                }
                
                // 查询并更新用户账号
                var user = await DC.Set<FrameworkUser>()
                    .FirstOrDefaultAsync(u => u.PersonId == person.ID);
                if (user != null)
                {
                    // 添加新岗位（有值才写入）
                    if (Entity.JobPositionId.HasValue)
                    {
                        // 先删除原有的岗位信息
                        await DC.Set<SysUserJobPosition>()
                            .Where(e => e.UserId == user.ID)
                            .ExecuteDeleteAsync();

                        // 添加新的岗位信息
                        var newJobPosition = new SysUserJobPosition
                        {
                            UserId = user.ID,
                            JobPositionId = Entity.JobPositionId.Value
                        };
                        await DC.Set<SysUserJobPosition>().AddAsync(newJobPosition);
                        await DC.SaveChangesAsync();

                        // 更新用户所属组
                        var jobPositionVm = new SysUserJobPositionVm
                        {
                            DC = this.DC,
                            Wtm = this.Wtm
                        };
                        await jobPositionVm.UpdateUserGroupAsync(user.ID);

                        // 刷新用户缓存
                        await Wtm.RemoveUserCache(user.ITCode);
                    }
                }
                
                await DC.SaveChangesAsync();
                transactionScope.Complete();
                
            }
            catch (Exception e)
            {
                MSD.AddModelError(" ", $"岗位分配操作失败: {e.Message}");
            }
        }
    }
}